package com.pzb.web.controller.wechat;
import com.alibaba.fastjson.JSONObject;
import com.pzb.common.config.WechatConfig;
import com.pzb.common.core.domain.AjaxResult;
import com.pzb.common.utils.wechat.WXBizMsgCrypt;
import com.pzb.common.utils.wechat.WXXmlToMapUtil;
import com.pzb.wechat.domain.TemplateUploadModel;
import com.pzb.wechat.domain.WechatApplet;
import com.pzb.wechat.domain.WechatAuthorization;
import com.pzb.wechat.domain.WechatComponent;
import com.pzb.wechat.service.IWechatAppletService;
import com.pzb.wechat.service.IWechatAuthorizationService;
import com.pzb.wechat.service.IWechatComponentService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;


/**
 * 微信操作处理
 * 
 * @author pzb
 */
@RestController
@RequestMapping("/wechat")
public class WechatController
{

    private static final Logger log = LoggerFactory.getLogger(WechatController.class);
    @Autowired
    private IWechatComponentService componentService;
    @Autowired
    private IWechatAuthorizationService authorizationService;
    @Autowired
    private IWechatAppletService appletService;
    /**
     * 生成验证码
     */
    @PostMapping("/getticket")
    public String getCode(HttpServletRequest request, HttpServletResponse response)
    {
        log.info("=================收到微信服务器回调====================");
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            // 微信加密签名
            String msg_signature = request.getParameter("msg_signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 从请求中读取整个post数据
            InputStream inputStream;
            inputStream = request.getInputStream();
            String postData= IOUtils.toString(inputStream, "UTF-8");    //获取接收到消息里的XML密文，存放在postData中
            WXBizMsgCrypt pc = new WXBizMsgCrypt(WechatConfig.getComponentToken(), WechatConfig.getAesKey(), WechatConfig.getAppId());
            String xml = pc.decryptMsg(msg_signature, timestamp, nonce, postData);
            Map<String, String> result = WXXmlToMapUtil.xmlToMap(xml);// 将xml转为map
            log.info("解密后数据====================》"+result);
            String InfoType = result.get("InfoType");  //获取infotype,注：微信开放平台文档中标明固定为："component_verify_ticket"
            if("component_verify_ticket".equals(InfoType)){
                //保存票据
                WechatComponent component = new WechatComponent();
                component.setTicket(result.get("ComponentVerifyTicket"));
                component.setTicketCreateTime(new Date(Long.parseLong(result.get("CreateTime")+"000")));
                componentService.updateWechatComponent(component);
            }else if("authorized".equals(InfoType) || "updateauthorized".equals(InfoType)){ //授权
                //获取用户授权信息
                String authorizationCode = result.get("AuthorizationCode");
                JSONObject res= componentService.queryAuth(authorizationCode);
                JSONObject re=res.getJSONObject("authorization_info");
                String authorizerAppid = result.get("AuthorizerAppid");
                //获取授权方账号信息
                JSONObject auth= componentService.getAuthorizerInfo(authorizerAppid);
                JSONObject js = auth.getJSONObject("authorizer_info");
                WechatAuthorization authorization = authorizationService.selectWechatAuthorizationByAuthorizerAppid(authorizerAppid);
                WechatApplet applet = appletService.selectWechatAppletByAppid(authorizerAppid);
                if(applet!=null){
                    applet.setNickName(js.getString("nick_name"));
                    applet.setPrincipalName(js.getString("principal_name"));
                    applet.setSignature(js.getString("signature"));
                    JSONObject business_info = js.getJSONObject("business_info");
                    applet.setOpenPay(business_info.getString("open_pay"));
                    appletService.updateWechatApplet(applet);
                }
                if(authorization == null){
                    authorization=new WechatAuthorization();
                    authorization.setAuthorizerAppid(authorizerAppid);
                    authorization.setAuthorizationCode(authorizationCode);
                    authorization.setAuthorizationCodeExpiredTime(new Date(Long.parseLong(result.get("AuthorizationCodeExpiredTime")+"000")));
                    authorization.setCreateTime(new Date(Long.parseLong(result.get("CreateTime")+"000")));
                    authorization.setAuthStatus(0);
                    authorization.setAuthorizerAccessToken(re.getString("authorizer_access_token"));
                    authorization.setExpiresIn(re.getString("expires_in"));
                    authorization.setAuthorizerRefreshToken(re.getString("authorizer_refresh_token"));
                    authorization.setFuncInfo(re.getString("func_info"));
                    authorization.setQrcodeUrl(js.getString("qrcode_url"));
                    authorization.setRefreshTime(new Date());
                    authorizationService.insertWechatAuthorization(authorization);
                }else {
                    authorization.setAuthorizerAppid(authorizerAppid);
                    authorization.setAuthorizationCode(authorizationCode);
                    authorization.setAuthorizationCodeExpiredTime(new Date(Long.parseLong(result.get("AuthorizationCodeExpiredTime")+"000")));
                    authorization.setCreateTime(new Date(Long.parseLong(result.get("CreateTime")+"000")));
                    authorization.setAuthStatus(0);
                    authorization.setAuthorizerAccessToken(re.getString("authorizer_access_token"));
                    authorization.setExpiresIn(re.getString("expires_in"));
                    authorization.setAuthorizerRefreshToken(re.getString("authorizer_refresh_token"));
                    authorization.setFuncInfo(re.getString("func_info"));
                    authorization.setQrcodeUrl(js.getString("qrcode_url"));
                    authorization.setRefreshTime(new Date());
                    authorizationService.updateWechatAuthorization(authorization);
                }
            }else if("unauthorized".equals(InfoType)){
                String authorizerAppid = result.get("AuthorizerAppid");
                WechatAuthorization authorization = authorizationService.selectWechatAuthorizationByAuthorizerAppid(authorizerAppid);
                if(authorization!=null){
                    authorization.setUnAuthorizationCodeExpiredTime(new Date(Long.parseLong(result.get("CreateTime"))));
                    authorization.setAuthStatus(1);
                    authorizationService.updateWechatAuthorization(authorization);
                }
            }
        } catch (Exception e) {
            log.error("Exception", e);
        }
        return "success";
    }


    //获取授权链接
    @GetMapping("/getAuthorizationLink/{appid}")
    public String getAuthorizationLink(@PathVariable String appid){
        System.err.println("biz_appid:"+appid);
        String preauthcode=componentService.createPreauthcode();
        String component_appid = WechatConfig.getAppId();
        String uri = "https://www.bluesharksys.com/success";
        String link = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&no_scan=1&component_appid="+component_appid+"&pre_auth_code="+preauthcode+"&scope=snsapi_userinfo&redirect_uri="+uri+"&auth_type=2&biz_appid="+appid;
        return link;
    }

    //获取代码草稿列表
    @GetMapping("/gettemplatedraftlist")
    public AjaxResult gettemplatedraftlist(){
        JSONObject result = componentService.gettemplatedraftlist();
        return AjaxResult.success(result);
    }

    //删除代码草稿
    @GetMapping("/gettemplatelist")
    public AjaxResult gettemplatelist(){
        JSONObject result = componentService.gettemplatelist();
        return AjaxResult.success(result);
    }

    //添加代码草稿
    @PostMapping("/addtotemplate")
    public AjaxResult addtotemplate(@RequestBody Map param){
        Integer draft_id = (Integer) param.get("draft_id");
        Integer  template_type = (Integer) param.get("template_type");
        JSONObject result = componentService.addtotemplate(draft_id,template_type);
        return AjaxResult.success(result);
    }

    //代码上传
    @PostMapping("/templateUpload")
    public AjaxResult templateUpload(@RequestBody TemplateUploadModel uploadModel){
        JSONObject result = componentService.templateUpload(uploadModel);
        return AjaxResult.success(result);
    }

    //接口测试
    @PostMapping("/test")
    public String test(){
        return authorizationService.getAuthorizerAccessToken("wx4f91df89416893c2");
    }
}
